package com.microinvest.service.impl;

import com.microinvest.dao.CreateStockMapper;
import com.microinvest.service.StockCountService;
import com.microinvest.util.ChangeListAndJsonUtil;
import com.microinvest.util.Result;
import com.microinvest.util.StockPriceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class StockCountServiceImpl implements StockCountService {

   private  StockPriceUtil stockPriceUtil;
   private ChangeListAndJsonUtil changeListToJsonUtil;
   private final CreateStockMapper createStockMapper;

   @Autowired
   public StockCountServiceImpl(CreateStockMapper createStockMapper){
//       this.changeListToJsonUtil=changeListToJsonUtil;
//       this.stockPriceUtil=stockPriceUtil;
       this.createStockMapper=createStockMapper;
    }
   @Override
   public Result createStock(String StockName,double FirstPrice) throws Exception {

       double RandowFirstPrice =stockPriceUtil.RandowANum(FirstPrice);

       // **1. 查询数据库中的原始 JSON**
       String oldJson = createStockMapper.getStockMessage(StockName);
       List<List<Double>> stockDataList = new ArrayList<>();

       if (oldJson != null && !oldJson.isEmpty()) {
           // **2. 解析 JSON 转为 List<List<Double>>**
           stockDataList = changeListToJsonUtil.ChangeToList(oldJson);
       }

       // **3. 生成 240 个新数据**
       List<Double> newData = stockPriceUtil.CreatStockPrice(RandowFirstPrice, 240, 10);

       // **4. 追加新数据作为一个新的子列表**
       stockDataList.add(newData);

       // **5. 转换为 JSON**
       String jsonResult = changeListToJsonUtil.ChangeToJson(stockDataList);

       // **6. 存入数据库**
       createStockMapper.insertStockData(StockName, jsonResult);
       return Result.success();
   }

    @Override
    public Result<List<String>> getStockMessage(String stockName) throws Exception {
        String stockJson = createStockMapper.getStockMessage(stockName);
        List<List<Double>> stockDataList;
        stockDataList = changeListToJsonUtil.ChangeToList(stockJson);
        List<String> result = new ArrayList<>();
        for (List<Double> subList : stockDataList) {
            // 将每个子列表的数字转换为字符串，并将其加入 List<String>
            result.add(subList.toString());
        }
       return Result.success(result);
    }
}
